package org.model.common.mybatis;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.KeySequence;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;

/**
 * mysql key 生成器.
 * 函数
 * CREATE FUNCTION IF NOT EXISTS next_val(pk_name varchar(50)) RETURNS BIGINT(20)
 * BEGIN
 * DECLARE maxId BIGINT(20);
 * SET maxId = 0;
 * SELECT next_val INTO maxId FROM id_seq WHERE sequence_name = pk_name;
 * SET maxId = maxId + 1;
 * UPDATE id_seq SET next_val = maxId WHERE sequence_name = pk_name;
 * RETURN maxId;
 * END
 * 建表语句
 * DROP TABLE IF EXISTS `id_seq`;
 * CREATE TABLE `id_seq` (
 * `pk_name` varchar(100) NOT NULL,
 * `next_val` bigint(20) DEFAULT NULL,
 * PRIMARY KEY (`pk_name`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
 *
 * @author Luo
 * @date 2024-09-05 9:23
 */
public class MysqlKeyGenerator implements IKeyGenerator {

    /**
     * 执行 key 生成 SQL
     *
     * @param incrementerName 序列名称(对应类上注解 {@link KeySequence#value()} 的值)
     * @return sql
     */
    @Override
    public String executeSql(final String incrementerName) {
        return "select next_val('" + incrementerName + "')";
    }

    /**
     * 数据库类型
     */
    @Override
    public DbType dbType() {
        return DbType.MYSQL;
    }

}
